package com.zhang.servlet.album;

import com.zhang.repository.RelationRepo;
import com.zhang.util.Log;
import com.zhang.view_object.UserVO;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author happy
 **/
@WebServlet("/studio/album/add.do")
public class AddDoServlet extends HttpServlet {
    private final RelationRepo relationRepo = new RelationRepo();
    @Override
    @SneakyThrows
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        Log.println("访问/studio/album/add.do");
        UserVO currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        if (currentUser == null) {
            Log.println("UploadDoServlet用户未登录");
            writer.println("该功能需要登录后才能使用");
            return;
        }


        req.setCharacterEncoding("utf-8");
        int aid = Integer.parseInt(req.getParameter("aid"));
        String[] tidArray = req.getParameterValues("add-tid");
        List<Integer> tidList = Arrays.stream(tidArray).map(Integer::parseInt).collect(Collectors.toList());
        relationRepo.insert(aid,tidList);


//        resp.setCharacterEncoding("utf-8");
//        resp.setContentType("application/json");
//        resp.getWriter().println("绑定成功");
        Log.println("DEBUG:专辑"+aid+"绑定音频成功");
        resp.sendRedirect("/studio/album/bind.html?aid="+aid);
    }
}